package controller.camera;

import javax.vecmath.*;
import javax.media.j3d.*;

public class Camera {

	private final View view = new View();

	public final static Vector3d DEFAULT_UP = new Vector3d(0, 1, 0);

	private TransformGroup tg = null;
	
	private final Transform3D localToVWorld = new Transform3D();
	
	private final Point3d camPos = new Point3d();

	public BranchGroup createView(Canvas3D cv) {
		View view = new View();
		//view.setProjectionPolicy(View.PARALLEL_PROJECTION);
		ViewPlatform vp = new ViewPlatform();
		view.addCanvas3D(cv);
		view.attachViewPlatform(vp);
		view.setPhysicalBody(new PhysicalBody());
		view.setPhysicalEnvironment(new PhysicalEnvironment());
		tg = new TransformGroup();
		tg.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
		tg.setCapability(TransformGroup.ALLOW_LOCAL_TO_VWORLD_READ);
		tg.addChild(vp);
		BranchGroup bgView = new BranchGroup();
		bgView.addChild(tg);
		
		lookAt(new Point3d(1, 1, 1), new Point3d(0,0,0), DEFAULT_UP);
		
		return bgView;
	}
	
	public Transform3D getLocalToVWorld() {
		return new Transform3D(localToVWorld);
	}

	public void lookAt(Point3d eye, Point3d look, Vector3d up) {
		Transform3D transform = new Transform3D();
		transform.lookAt(eye, look, DEFAULT_UP);
		try {
			transform.invert();
		} catch (javax.vecmath.SingularMatrixException e) {
			System.err.println("Mulig kamerabug.");
			return;
		}
		tg.setTransform(transform);
		tg.getLocalToVworld(localToVWorld);
		camPos.set(eye);
	}

	public void lookAt(Point3d eye, Point3d look) {
		this.lookAt(eye, look, DEFAULT_UP);		
	}

	public View getView() {
		return view;
	}
	
	public Point3d getPos() {
		return camPos;
	}
}
